<template>
  <div>
    <header>
      <div class="search-return" @click="goBack">
        <i class="iconfont icon-fanhui"></i>
      </div>
      <div class="search-main">
        <i class="iconfont icon-fangdajing"></i>
        <form action="" onsubmit="return false" @keyup.enter="goSearchList">
          <input
            ref="myInput"
            type="search"
            placeholder="搜索你喜欢的产品..."
            v-model="searchVal"
            autofocus
          />
        </form>
      </div>
      <div class="search-btn" @click="goSearchList">搜索</div>
    </header>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchVal: this.$route.query.key || "",
      searchArr:[]
    };
  },
  mounted() {
    // 键盘监听事件
    window.addEventListener("touchmove", this.myTouchMove, true);
  },
  methods: {
    //  失去焦点
    myTouchMove() {
      this.$refs.myInput.blur();
    },

    goBack() {
      this.$router.back();
    },
    goSearchList() {
      if(!this.searchVal) return;

      if(!localStorage.getItem('searchList')) {
        localStorage.setItem('searchList','[]');
      }else{
        this.searchArr = JSON.parse(localStorage.getItem('searchList'));
      }
      //增加数据
      this.searchArr.unshift(this.searchVal);

      //去重es6 new Set和数组转换Array.from()
      let newArr = new Set(this.searchArr)
     

      //给本地赋值
      localStorage.setItem('searchList',JSON.stringify(Array.from(newArr)));
      
      //路径如果没有变化，不跳转页面
      if(this.searchVal === this.$route.query.key) return ;

      //跳转页面
      this.$router.push({
          name:'search-list',
          query:{
            key:this.searchVal
          }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 1.2571rem;
  color: #fff;
  background-color: #b0352f;
}
.search-return,
.search-btn {
  padding: 0 0.2857rem;
}
.search-return i {
  font-size: 0.5714rem;
}
.search-main {
  display: flex;
  align-items: center;
  width: 7rem;
  height: 0.8571rem;
  border-radius: 1.3429rem;
  background-color: #fff;
  i {
    color: #000;
    padding: 0 0.2857rem;
  }
  form {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    input {
      width: 100%;
      font-size: 0.4rem;
      color: #000;
      padding: 0 0.1429rem;
    }
  }
} 
.search-btn {
  font-size: 0.4rem;
}
</style>
